YSearch = function() {}

YSearch.init = function(site, results) {
	YSearch.site = site || 'as-is.net';
	YSearch.results = results || 10;
	YSearch.queryElement = document.getElementById('ysearch-query');
	YSearch.displayElement = document.getElementById('ysearch-display');
}

YSearch.doLoad = function(c, r) {
	if (!r) return;
	eval("var res = " + r);
	var results = res['Result'];
	var firstResultPosition = res['firstResultPosition'];
	var totalResultsReturned = res['totalResultsReturned'];
	var totalResultsAvailable = res['totalResultsAvailable'];

	var html = '';
	if (totalResultsReturned > 0) {
		var prevpos = firstResultPosition - YSearch.results;
		var nextpos = firstResultPosition + YSearch.results;

		html += '<ul>';
		for (var i in results) {
//			html += '<li><a href="'+results[i].Url+'" title="'+results[i].Summary+'">'+results[i].Title+'</a></li>';
			html += '<li><a href="'+results[i].Url+'">'+results[i].Title+'</a><br />'+results[i].Summary+'</li>';
		}
		html += '</ul>';

		if (prevpos > 0) {
			html += '<input type="button" value="Prev" onclick="YSearch.query('+prevpos+')" />';
		} else {
			html += '<input type="button" value="Prev" disabled="disabled" />';
		}
		if (nextpos < totalResultsAvailable && nextpos <= 1000) {
			html += '<input type="button" value="Next" onclick="YSearch.query('+nextpos+')" />';
		} else {
			html += '<input type="button" value="Next" disabled="disabled" />';
		}
	} else {
		html += 'No results.';
	}
	html += '<input type="button" value="Close" onclick="YSearch.clear()" />';
	YSearch.display(html);
}

YSearch.doLoading = function(c) {
	YSearch.display('Now loading...');
}

YSearch.query = function(s) {
	var query = YSearch.queryElement.value;
	if (!query) return;
	var start = s || 1;
	AjaxClient.call({
		'load': YSearch.doLoad,
		'loading': YSearch.doLoading,
		'uri': 'ysearch-json.fcgi',
		'method': 'GET',
		'args': {
			'query': query,
			'type': 'all',
			'results': YSearch.results,
			'start': start,
			'format': 'any',
			'language': 'ja',
			'site': YSearch.site
		}
	});
}

YSearch.display = function(t) {
	YSearch.displayElement.style.display = 'block';
	YSearch.displayElement.innerHTML = t;
}
YSearch.clear = function() {
	YSearch.displayElement.style.display = 'none';
	YSearch.displayElement.innerHTML = '';
}
